package cn.tedu._07springaop.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Aspect
@Component
//切面类
public class LogAspect {
    @Before(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))")
    public void before(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();//获取目标方法名
        Object args = Arrays.toString(joinPoint.getArgs());//获取目标方法的参数列表
        System.out.println("前置通知" + name + args);
    }
    @After(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))")
    public void after(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        System.out.println("后置通知" + name);
    }

    @AfterReturning(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))", returning = "result")//注意返回值类型
    public void afterReturning(JoinPoint joinPoint, Object result) {
        String name = joinPoint.getSignature().getName();
        System.out.println("返回通知" + name + result);
    }
    @AfterThrowing(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))", throwing = "result")//注意返回值类型
    public void afterThrowing(JoinPoint joinPoint, Exception result) {
        String name = joinPoint.getSignature().getName();
        System.out.println("异常通知" + name + result);
    }

    @Around(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) {
        Object result = null;
        try {
            String name = joinPoint.getSignature().getName();
            System.out.println("环绕通知-前置通知" + name);
            result = joinPoint.proceed();
            System.out.println("环绕通知-返回通知" + name + result);
        } catch (Throwable e) {
            String name = joinPoint.getSignature().getName();
            System.out.println("环绕通知-异常通知" + name + e);
        }
        return result;
    }
}
